﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace HPPUtil
{
    public class SerializeHelper
    {
        /// <summary>
        /// 序列化保存对象
        /// </summary>
        /// <param name="saveFileName">保存到的文件名称</param>
        /// <param name="saveObject">要保存的对象</param>
        /// <returns>是否保存成功</returns>
        public static bool Serialize(object saveObject, string saveFileName)
        {
            try
            {
                using (FileStream fs = new FileStream(saveFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                {
                    BinaryFormatter b = new BinaryFormatter();
                    b.Serialize(fs, saveObject);
                }

            }
            catch (Exception ex)
            {
                CommonLogger.Logger.Error(string.Format("In Serialize(), saveFileName:{0}", saveFileName), ex);
                
                return false;
            }
            return true;
        }

        public static object DeSerialize(string saveFileName)
        {
            object obj = null;
            try
            {
                using (FileStream fs = new FileStream(saveFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    fs.Seek(0, SeekOrigin.Begin);
                    BinaryFormatter b = new BinaryFormatter();
                    obj = b.Deserialize(fs);
                }
            }
            catch (Exception ex)
            {
                CommonLogger.Logger.Error(string.Format("In DeSerialize(), saveFileName:{0}", saveFileName), ex);
                return null;
            }

            return obj;
        }
    }
}
